const router = require('koa-router')()
const userServices = require('../controllers/mySqlConfig')

router.prefix('/note')//接口前缀

//查找noteType
router.post('/findNoteListByType', async (ctx, next) => {
    let _note_type = ctx.request.body.note_type
    await userServices.findNoteType(_note_type).then(res => {
        console.log(res);
        if (res.length > 0) {
            let result = []
            for (let i = 0; i < res.length; i++) {
                let obj = {}
                obj['id'] = res[i].id
                obj['title'] = res[i].title
                obj['c_time'] = res[i].c_time
                obj['head_img'] = res[i].head_img
                result.push(obj)
            }
            ctx.body = {
                code: 200,
                data: result,
                mess: '查询成功'
            }
        } else {
            ctx.body = {
                code: 80005,
                data: 'null',
                mess: '数据为空'
            }
        }
    }).catch(err => {
        console.log(err);
        ctx.body = {
            code: 80002,
            data: 'error',
        }
    })

})

//查找noteDetail
router.get('/noteDetail', async (ctx, next) => {
    let _id = ctx.request.query.id
    console.log(_id);
    await userServices.getNoteDetail(_id).then(res => {
        console.log(res);
        if (res.length > 0) {
            ctx.body = {
                code: 200,
                data: res,
                mess: '查询成功'
            }
        } else {
            ctx.body = {
                code: 80005,
                data: 'null',
                mess: '数据为空'
            }
        }
    }).catch(err => {
        console.log(err);
        ctx.body = {
            code: 80002,
            data: 'error',
        }
    })

})

//发布文章
router.post('/publish',async (ctx,next)=>{
    let _username = ctx.request.body.username
    let _note_type = ctx.request.body.note_type
    let _title = ctx.request.body.title
    let _head_img = ctx.request.body.head_img
    let _note_content = ctx.request.body.note_content
    let _useId = 0
    let _nickname = ''
    let date = new Date()
    let c_time = date.getFullYear()+'年'+date.getMonth()+1+'月'+date.getDay().toString().padStart(2,0)+'日'
    let m_time = date.getFullYear()+'年'+date.getMonth()+1+'月'+date.getDay().toString().padStart(2,0)+'日'
    await userServices.findUser(_username).then(res=>{
      _useId = res[0].id
      _nickname = res[0].nickname
      // console.log(res[0].id);
    })
    console.log(ctx.request.body);
    await userServices.publishNote([_useId,_title,_note_type,_note_content,c_time,m_time,_head_img,_nickname]).then(res=>{
      console.log(res);
      
        ctx.body = {
          code:200,
          data: 'ok',
          mess: '发布成功'
        }
      
    })
    
    
  })
  

module.exports = router



